package demo.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import util.JsonUtil;

import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Map;

public class MapEncoder extends MessageToByteEncoder<Map<String, String>> {
    // TODO Use CharsetEncoder instead.
    private final Charset charset;

    /**
     * Creates a new instance with the current system character set.
     */
    public MapEncoder() {
        charset = Charset.defaultCharset();
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Map<String, String> msg, ByteBuf out) throws Exception {
        if (msg == null) {
            return;
        }
        String s = JsonUtil.beanToJson(msg);

//        out.add();
        ByteBuf byteBuf = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(s), charset);
        out.writeBytes(byteBuf, byteBuf.readerIndex(), byteBuf.readableBytes());
    }
}
